package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.NumberUtils;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public Boolean check(String data, Integer type) {

        User record = new User();

        switch(type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
        }

        Boolean result=this.userMapper.selectCount(record)!=1;

        if(null==result){
            throw new LyException(ExceptionEnum.USER_CHECK_FAILD);
        }

        return result;
    }

    static final String KEY_PREFIX="ly:sms:phone";

    public void sendVertifyCode(String phone) {

        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }

        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        String code = NumberUtils.generateCode(6);
        msg.put("code",code);

        try {

            amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);

            redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);

        } catch (AmqpException e) {
            throw new LyException(ExceptionEnum.SMS_SEND_ERROR);
        }
    }

    public void createUser(User user, String code) {
        String storeCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if(!code.equals(storeCode)){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.userMapper.insertSelective(user);
        redisTemplate.delete(KEY_PREFIX + user.getPhone());
    }

    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        User record = new User();
        record.setUsername(username);
        User storeUser = this.userMapper.selectOne(record);
        if(storeUser==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        if(!passwordEncoder.matches(password, storeUser.getPassword())){
            // 密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return BeanHelper.copyProperties(storeUser,UserDTO.class);
    }
}
